package com.fan.teamer.security;

import java.util.ArrayList;
import java.util.Collection;

import javax.inject.Inject;
import javax.inject.Named;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.transaction.annotation.Transactional;

import com.fan.teamer.model.dao.RoleDao;
import com.fan.teamer.model.domain.Member;
import com.fan.teamer.model.domain.Role;

@Named("assembler")
public class Assembler {

	@Inject
	@Named("roleDao")
	private RoleDao roleDao;

	public RoleDao getRoleDao() {
		return roleDao;
	}

	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	@Transactional(readOnly = true)
	User buildUserFromUserEntity(Member member) {

		String username = member.getEmail();
		String password = member.getPassword();

		boolean enabled = false;

		if (member.getEnabled() == 1) {
			enabled = true;
		} else {
			enabled = false;
		}
		boolean accountNonExpired = enabled;
		boolean credentialsNonExpired = enabled;
		boolean accountNonLocked = enabled;

		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (Role role : roleDao.getAllRoles()) {
			authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
		}

		User user = new User(username, password, enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, authorities);
		return user;
	}
}